<?php

namespace app\admin\model\scanwork;
use think\facade\Db;


use think\Model;

class Process extends Model
{
    // 表名
    protected $name = 'scanwork_process';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'process_type_text',
        'skill_level_text'
    ];
    
    public function getStatusList()
    {
        return ['0' => __('禁用'), '1' => __('正常')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 工序类型
    public function getProcessTypeList()
    {
        return [
            'standard' => __('标准工序'),
            'special' => __('特殊工序')
        ];
    }

    public function getProcessTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['process_type']) ? $data['process_type'] : '');
        $list = $this->getProcessTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 技能等级
    public function getSkillLevelList()
    {
        return [
            'basic' => __('基础'),
            'intermediate' => __('中级'),
            'advanced' => __('高级')
        ];
    }

    public function getSkillLevelTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['skill_level']) ? $data['skill_level'] : '');
        $list = $this->getSkillLevelList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 获取工序编码
    public function getProcessCodeAttr($value, $data)
    {
        if (empty($value) && isset($data['id'])) {
            $value = 'GX-' . str_pad($data['id'], 3, '0', STR_PAD_LEFT);
        }
        return $value;
    }

    // 检查工序编码是否唯一
    public function checkCodeUnique($code, $id = null)
    {
        $where = ['process_code' => $code];
        if ($id) {
            $where['id'] = ['<>', $id];
        }
        return $this->where($where)->count() == 0;
    }

    // 获取质检要求
    public function getQualityRequirementsAttr($value, $data)
    {
        if (is_string($value)) {
            return json_decode($value, true) ?: [];
        }
        return $value ?: [];
    }

    // 设置质检要求
    public function setQualityRequirementsAttr($value, $data)
    {
        if (is_array($value)) {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }
        return $value;
    }

    // 获取操作步骤
    public function getOperationStepsAttr($value, $data)
    {
        if (is_string($value)) {
            return json_decode($value, true) ?: [];
        }
        return $value ?: [];
    }

    // 设置操作步骤
    public function setOperationStepsAttr($value, $data)
    {
        if (is_array($value)) {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }
        return $value;
    }

    // 获取所需设备
    public function getEquipmentRequiredAttr($value, $data)
    {
        if (is_string($value)) {
            return json_decode($value, true) ?: [];
        }
        return $value ?: [];
    }

    // 设置所需设备
    public function setEquipmentRequiredAttr($value, $data)
    {
        if (is_array($value)) {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }
        return $value;
    }

    // 关联工序工价
    public function processPrices()
    {
        return $this->hasMany('app\admin\model\scanwork\ProcessPrice', 'process_id', 'id');
    }

    // 关联分工分配
    public function allocations()
    {
        return $this->hasMany('app\admin\model\scanwork\Allocation', 'process_id', 'id');
    }

    // 关联报工记录
    public function reports()
    {
        return $this->hasMany('app\admin\model\scanwork\Report', 'process_id', 'id');
    }

    // 获取工序统计信息
    public function getProcessStats()
    {
        $allocationCount = $this->allocations()->count();
        $totalAllocated = $this->allocations()->sum('quantity');
        $totalReported = $this->allocations()->sum('reported_quantity');
        $totalHours = $this->allocations()->sum('actual_hours');
        
        return [
            'allocation_count' => $allocationCount,
            'total_allocated' => $totalAllocated,
            'total_reported' => $totalReported,
            'completion_rate' => $totalAllocated > 0 ? round($totalReported / $totalAllocated * 100, 2) : 0,
            'total_hours' => $totalHours
        ];
    }

    // 获取工序工价统计
    public function getPriceStats()
    {
        $prices = $this->processPrices()->select();
        $priceCount = count($prices);
        $avgPrice = $priceCount > 0 ? $prices->avg('price') : 0;
        $avgTimePrice = $priceCount > 0 ? $prices->avg('time_price') : 0;
        
        return [
            'price_count' => $priceCount,
            'avg_price' => round($avgPrice, 2),
            'avg_time_price' => round($avgTimePrice, 2),
            'min_price' => $priceCount > 0 ? $prices->min('price') : 0,
            'max_price' => $priceCount > 0 ? $prices->max('price') : 0
        ];
    }

    // 检查工序是否被使用
    public function isUsed()
    {
        $allocationCount = $this->allocations()->count();
        $priceCount = $this->processPrices()->count();
        
        return $allocationCount > 0 || $priceCount > 0;
    }

    // 获取可操作此工序的员工
    public function getOperableEmployees()
    {
        $employees = \app\admin\model\scanwork\Employee::where('status', 1)->select();
        $operableEmployees = [];
        
        foreach ($employees as $employee) {
            $operableProcesses = $employee->operable_processes;
            if (in_array($this->id, $operableProcesses)) {
                $operableEmployees[] = $employee;
            }
        }
        
        return $operableEmployees;
    }
} 